package com.sunye.redis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;


/**
 * redis过期监听(配置redisConfig文件)
 */
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {



    @Autowired
    protected RedisService redis;


    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //得到过期的键
        String key = new String(message.getBody(), StandardCharsets.UTF_8);

        /**
         * 付款十分钟后未完善 发送短信
         */
        if (key.length() > 23 && "orderCultureNotPerfect:".equals(key.substring(0, 23))) {
            //插入一条数据， 充当锁; 设置30分钟过期
            String lock = redis.getAndSet("lock:" + key + ".lock", "1", 30L);
            if ("1".equals(lock)) {
                return;
            }
            String id = key.substring(23);
            //TODO 处理业务逻辑
        }
    }
}

